<template>
  <div>
    <ButtonGroup
      :options="buttons"
      class="button-container"
      @click="handleButtonClick"
    />
    <p-table
      :custom-header-row="customHeaderRowMinxin"
      row-key="id"
      :columns="columns"
      bordered
      :scroll="{ x: 'calc(1400px + 20%)', y: 300 }"
      :pagination="false"
      :data-source="dataSource"
      :row-selection="rowSelectionMixin"
      size="middle"
      @change="handleTableChange"
    >
    </p-table>
    <!-- <DialogSaveTemplate
      :visible.sync="visibleDialog"
      :data-source="templateData"
      :sales-organization="parentId"
      @change="handleDialogChange"
    />
    <DialogUseTemplate
      :visible.sync="visibleDialogUse"
      :sales-organization="parentId"
      @change="handleDialogUseChange"
    /> -->
    <DialogPriceChangeList
      :visible="visible"
      :forms="forms"
      :time-range="timeRange"
      :key-array="keyArray"
      :delete-keys="deleteKeys"
      :res-key.sync="resKey"
      @cancel="$emit('update:visible', false)"
      @pass-datearr="takeDateArr"
      @select-keys="selectKeys"
    />
    <DialogBpForecastRelationList
      :value="currentRowInfo.value"
      :visible="visibleBpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.bpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleBpId = val)"
      @change="(e) => confirmDialog(e)"
    />
    <DialogRpRelationList
      :value="currentRowInfo.value"
      :visible="visibleRpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.rpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleRpId = val)"
      @change="(e) => confirmDialog(e)"
    />
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
// import SelectUser from '@/components/select/SelectUser.vue';
import DialogPriceChangeList from '@/components/dialog/DialogPriceChangeList.vue';
import { postOrganizationInfo } from '@/api/public.js';
import DrawerMixin from '@/views/price-change/components/mixin';
import DialogBpForecastRelationList from '@/components/dialog/DialogBpForecastRelationList.vue';
import DialogRpRelationList from '@/components/dialog/DialogRpRelationList.vue';
import ColumnsTooltip from '@/views/price-change/components/columnsTooltip.vue';

import { createMonthArray } from '@/utils/time';
import monent from 'moment';

let index = 0;
const createDefaultItem = () => ({
  id: index++,
  salesGroup: '',
  kapmGroup: '',
  responsibleId: '',
  isTemplate: 0,
  templateName: undefined,
});
export default {
  components: {
    DialogPriceChangeList,
    DialogBpForecastRelationList,
    DialogRpRelationList,
  },
  mixins: [mixinTable, DrawerMixin],
  props: {
    keyArray: {
      type: Array,
      default: () => [],
    },
    isEmptyArray: {
      type: Boolean,
      default: false,
    },

    resSource: {
      type: Boolean,
      default: false,
    },
    formInfo: {
      type: Object,
      default: () => ({}),
    },
    resForm: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    parentId: {
      type: [String, Number],
      default: undefined,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    planId: {
      type: [String, Number],
      default: '',
    },
    forms: {
      type: Object,
      default: () => ({}),
    },
    buttons: {
      type: [Array],
      default: () => [
        {
          key: 'add',
          type: 'primary',
          label: '选择',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
        },
      ],
    },
    // columns: {
    //   type: [Array],
    //   default: () => [],
    // },
  },
  data() {
    return {
      copeSource: [],
      deleteKeys: [],
      orgGroupOptions: [],
      orgKapmOptions: [],
      isEdit: true,
      dateArr: [],
      dataSource: [],
      oldDataSource: [],
      keys: [],
      resKey: false,
      visibleBpId: false,
      visibleRpId: false,
      currentRowInfo: {},
    };
  },
  computed: {
    timeRange() {
      return [this.forms.startTime, this.forms.endTime];
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          // customRender(t, r, index) {
          //   return parseInt(index) + 1;
          // },
          customRender: (t, r, index) => {
            if (this.totalAllIndex.includes(index)) {
              return {
                children: (
                  <div style="display: flex;justify-content: flex-start;">
                    汇总
                  </div>
                ),
                attrs: {
                  colSpan: this.colIndex,
                },
              };
            }
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: 'M+9关系ID',
          dataIndex: 'm9RelationId',
          key: 'm9RelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联RP关系ID',
          dataIndex: 'rpRelationId',
          key: 'rpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleRpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'rpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联BP关系ID',
          dataIndex: 'bpRelationId',
          key: 'bpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleBpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'bpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '厂别',
          dataIndex: 'factoryCode',
          key: 'factoryCode',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.factoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelInfoName',
          key: 'modelInfoName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          key: 'modelName',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '料号',
          dataIndex: 'materialCode',
          key: 'materialCode',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '生产地',
          width: 80,
          dataIndex: 'manufactureArea',
          key: 'manufactureArea',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.productionPlaceOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          key: 'application',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.applicationOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '模切比',
          width: 80,
          dataIndex: 'modelCutRate',
          key: 'modelCutRate',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '形态',
          dataIndex: 'appearance',
          key: 'appearance',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.shapeOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户项目',
          dataIndex: 'item',
          key: 'item',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '内部项目',
          dataIndex: 'innerItem',
          key: 'innerItem',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '类别',
          dataIndex: 'category',
          key: 'category',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.categoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '备注',
          width: 100,
          dataIndex: 'remark',
          key: 'remark',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
      ];
      if (this.dateArr.length) {
        this.dateArr.forEach((date, i) => {
          columns.push({
            align: 'center',
            title: date,
            dataIndex: `priceMonth${i}`,
            width: 180,
            ellipsis: true,
            children: [
              {
                align: 'center',
                title: 'BP',
                dataIndex: `bpPriceMonth${date}`,
                key: `bpPrice${date}`,
                width: 60,
              },
              {
                align: 'center',
                title: 'RP',
                dataIndex: `rpPriceMonth${date}`,
                key: `rpPrice${date}`,
                width: 60,
              },
              {
                align: 'center',
                title: 'M+9',
                dataIndex: `priceMonth${date}`,
                key: `price${date}`,
                width: 60,
              },
              {
                align: 'center',
                title: '最新价格',
                dataIndex: `newPriceMonth${date}`,
                key: `newPrice${date}`,
                width: 80,
                ellipsis: true,
                scopedSlots: {
                  customRender: `newPriceMonth${date}`,
                },
                customRender: (value, row, index) => {
                  // console.log(value, row, index,'value, row, index-===123')
                  // let totalKeys = Object.keys(row).filter((item) =>
                  //   item.includes(`${date}`)
                  // );

                  // // console.log(totalKeys,'totalKeys -===123')

                  // let isDisabled = !totalKeys.length

                  const children = (
                    <div>
                      <p-tooltip title={value}>
                        <InputTable
                          isEdit={this.isEdit}
                          isNewPrice={true}
                          value={value}
                          vOn:change={(e) =>
                            this.handleInputChange(
                              e,
                              value,
                              row,
                              index,
                              `newPriceMonth${date}`
                            )
                          }
                        />
                      </p-tooltip>
                    </div>
                  );
                  return {
                    children,
                  };
                },
              },
            ],
          });
        });
      }
      // console.log(columns);
      return columns;
    },
    getSourceVal() {
      return this.dataSource || [];
    },
  },
  watch: {
    resSource: {
      handler(val) {
        console.log('val: ', val);
        if (val) {
          this.dataSource = [];
          this.deleteKeys = [];
          this.dateArr = [];
          this.keys = [];
          this.resKey = true;
          this.$emit('update:resSource', false);
        }
      },
    },
    dataSource: {
      handler(val) {
        if (val.length) {
          this.$emit('update:isEmptyArray', true);
        }
      },
      deep: true,
    },
    resForm: {
      handler(val) {
        if (val) {
          this.dataSource = [];
          this.dateArr = [];
        }
      },
      immediate: true,
    },
    parentId: {
      handler(val) {
        this.getDicList();
      },
      immediate: true,
    },
    formData: {
      handler(val) {
        let array = [];
        val.forEach((item) => {
          if (Object.keys(JSON.parse(item.price)).length > array.length) {
            array = JSON.parse(
              JSON.stringify(Object.keys(JSON.parse(item.price)))
            );
          }
        });
        this.dateArr = array;
        this.dataSource = this.proessData(val);
      },
      deep: true,
    },
  },
  created() {},
  methods: {
    openDialog(dialog, rowInfo) {
      this[dialog] = true;
      this.currentRowInfo = rowInfo;
      console.log('this.currentRowInfo: ', this.currentRowInfo);
    },
    selectKeys(val) {
      this.keys = val;
    },

    getDateArr(arr) {
      const startTime = monent(arr[0]).format('YYYY-MM');
      const endTime = monent(arr[1]).format('YYYY-MM');
      const ranges = createMonthArray([startTime, endTime]);
      return ranges;
    },
    getDataSource() {
      return this.getSourceVal || [];
    },
    takeDateArr(value) {
      console.log('value: ', value);
      this.copeSource = JSON.parse(JSON.stringify(value.rowData));
      this.dateArr = value.dateArr;
      this.getSourceVal = this.getSourceVal.map((item) => {
        if (item.price !== null) {
          item.price = JSON.parse(item.price);
          const price = this.dateArr.reduce((pre, cur) => {
            pre[cur] = item.price[cur];
            return pre;
          }, {});
          item.price = JSON.stringify(price);
        }
      });
      this.dataSource.push(...value.rowData);
    },
    async getDicList() {
      const result = await postOrganizationInfo({
        code: this.parentId || 'ltcsmsizebu',
      });
      const orgOptions = result?.data?.data || [];
      this.orgGroupOptions = orgOptions.filter((item) =>
        item.code?.includes('sales')
      );
      this.orgKapmOptions = orgOptions.filter((item) =>
        item.code?.includes('kapm')
      );
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      console.log('fn: ', fn);
      this[fn] && this[fn]();
    },
    addCallback() {
      this.$emit('validate');
      // this.dataSource.push({ ...createDefaultItem() });
      // this.visibleDialog = true;
    },
    deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      if (!ids.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`)
        .then(() => {
          ids.forEach((id) => {
            const index = this.dataSource.findIndex((item) => item.id === id);
            this.dataSource.splice(index, 1);
          });
          this.deleteKeys = JSON.parse(
            JSON.stringify(this.rowSelectionMixin.selectedRowKeys)
          );
          this.rowSelectionMixin.selectedRowKeys = [];
          if (this.dataSource.length === 0) {
            this.dateArr = [];
          }
        })
        .catch(() => {
          // console.log('e: ', e);
        });
    },

    handleDialogUseChange(val) {
      const copys = val.map((item) => {
        return {
          // ...item,
          isTemplate: 0,
          templateName: undefined,
          id: `copy_${item.id}`,
          responsibleId: {
            key: item.responsibleId,
            label: item.responsibleName,
          },
          salesGroup: {
            key: item.salesGroup,
            label: item.salesGroupName,
          },
          kapmGroup: {
            key: item.kapmGroup,
            label: item.kapmGroupName,
          },
        };
      });
      this.dataSource.push(...copys);
    },
  },
};
</script>

<style lang="less" scoped>
.item-container {
  display: flex;
  align-items: center;
}
.button-container {
  margin-bottom: 20px;
}

/deep/ .poros-select-selection {
  border: none;
}
</style>
